<?php

namespace app\common\logic;

use app\admin\model\Admin;
use app\common\library\exception\ApiException;
use app\common\library\MemberVo;
use app\common\model\CarModels;
use app\common\model\CarSeries;
use app\common\model\Collection;
use app\common\model\EnergyType;
use app\common\model\Member;
use app\common\model\Message;
use app\common\model\Service;
use app\common\model\ServiceImage;
use app\common\model\ServiceShop;
use app\common\model\Shop;
use app\common\model\UsedCar;
use fast\Date;
use think\db\Query;
use think\Env;
use think\Exception;
use think\Log;
use think\Queue;

class UsedCarLogic extends BaseLogic
{
    public $model;

    public function assignModel()
    {
        $this->model          = new UsedCar();
    }

    public function handleSearch(Query $query, array $params): Query
    {
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $whereOrRaw = "shop.shop_name  LIKE '%{$params['keywords']}%' or brand.name  LIKE '%{$params['keywords']}%' or series.name  LIKE '%{$params['keywords']}%'";
            $query->where($whereOrRaw);
        }
        if (isset($params['belong']) && !empty($params['belong'])) {
            if ($params['belong'] == 1){ //个人
                $query->where('type','eq',1);
            }elseif ($params['belong'] == 2){ //车商
                $query->where('type','eq',2);
            }elseif ($params['belong'] == 3){ //我发布的
                $query->where('member_id','eq',MemberVo::instance()->getMemberId());
            }
        }
        if (isset($params['status']) && !empty($params['status'])) {
            $query->where('used_car.status',$params['status']);
        }
        if (isset($params['is_del'])) {
            $query->where('used_car.is_del',$params['is_del']);
        }
        if (isset($params['show']) && !empty($params['show'])) {
            $query->where('used_car.show',$params['show']);
        }

        if (isset($params['brand_id']) && !empty($params['brand_id'])) {
            $query->where('used_car.brand_id',$params['brand_id']);
        }

        if (isset($params['series_id']) && !empty($params['series_id'])) {
            $query->where('used_car.series_id',$params['series_id']);
        }
        if (isset($params['models_id']) && !empty($params['models_id'])) {
            $query->where('models_id',$params['models_id']);
        }
        if (isset($params['level']) && !empty($params['level'])) {
            $query->where('used_car.level',$params['level']);
        }
        if (isset($params['car_type']) && !empty($params['car_type'])) {
            $query->where('car_type','eq',$params['car_type']);
        }
        if (isset($params['car_age_mix']) && !empty($params['car_age_mix'])) {
            $query->where('used_car.car_age','elt',strtotime(date("Y-m-01", strtotime("-{$params['car_age_mix']} year"))));
        }
        if (isset($params['car_age_max']) && !empty($params['car_age_max'])) {
            $query->where('used_car.car_age','egt',strtotime(date("Y-m-01", strtotime("-{$params['car_age_max']} year"))));
        }
        if (isset($params['price_mix']) && !empty($params['price_mix'])) {
            $query->where('used_car.price','egt',$params['price_mix']);
        }
        if (isset($params['price_max']) && !empty($params['price_max'])) {
            $query->where('used_car.price','elt',$params['price_max']);
        }
        if (isset($params['mileage_mix']) && !empty($params['mileage_mix'])) {
            $query->where('used_car.mileage','egt',$params['mileage_mix']);
        }
        if (isset($params['mileage_max']) && !empty($params['mileage_max'])) {
            $query->where('used_car.mileage','elt',$params['mileage_max']);
        }
        if (isset($params['city']) && !empty($params['city'])) {
            $query->where('used_car.city','eq',$params['city']);
        }
        if (isset($params['shop_id']) && !empty($params['shop_id'])) {
            $query->where('used_car.shop_id','eq',$params['shop_id']);
        }
        if (isset($params['member_id']) && !empty($params['member_id'])) {
            $query->where('used_car.member_id','eq',$params['member_id']);
        }
        if (isset($params['type']) && !empty($params['type'])) {
            $query->where('used_car.type','eq',$params['type']);
        }
        return $query;
    }

    /**
     * 二手车列表
     * @param array $params
     */
    public function index($params)
    {
        $params['status'] = 1;
        $params['is_del'] = 0;//是否删除
        $params['show'] = 1;//是否上架

        $params['with'] = ['series','brand','shop','member'];
        $params['orderBy'] = 'used_car.id';
        $params['orderType'] = 'desc';
        if (isset($params['sort'])){
            if ($params['sort'] == 0){ //默认排序
                $params['orderBy'] = 'used_car.id';
                $params['orderType'] = 'desc';
            }elseif ($params['sort'] == 1){ //最新上架
                $params['orderBy'] = 'used_car.id';
                $params['orderType'] = 'desc';
            }elseif ($params['sort'] == 2){ //里程最少
                $params['orderBy'] = 'used_car.mileage';
                $params['orderType'] = 'asc';
            }elseif ($params['sort'] == 3){ //价格最低
                $params['orderBy'] = 'used_car.price';
                $params['orderType'] = 'asc';
            }elseif ($params['sort'] == 4){ //车龄最短
                $params['orderBy'] = 'used_car.car_age';
                $params['orderType'] = 'desc';
            }
        }
        $params['field'] = 'id,car_age,mileage,phone,price,member_id,cover_img,down_payment,type,shop_id,longitude,latitude';
        return  $this->getPageList($params)->each(function (&$item){
            if ($item['type'] == 2){
                $item['shop_name'] = $item['shop']['shop_name'];
            }else{
                $item['shop_name'] = $item['member']['member_name'];
            }
            $dif =  getMonthNum($item['car_age'],time());
            $str = '';
            if ($dif[1] >0){
                $str = $dif[1].'年';
            }
            if ($dif[2] >0){
                $str = $str.$dif[2].'月';
            }
            $item['car_age'] = $str;
            $item['mileage'] = $item['mileage'].'万公里';
            $collection = Collection::get(['main_id'=>$item['id'],'service_type'=>1,'member_id'=>MemberVo::instance()->getMemberId()]);
            $item['is_collection'] = !empty($collection) ? 1 : 0;
            $item['collection_id'] = !empty($collection) ? intval($collection['id']) : 0;
            $item['price'] = sprintf("%01.2f", $item['price']).'万元';
            $item['down_payment'] = $item['down_payment'] ? sprintf("%01.2f", $item['down_payment']).'万元' : '';
            $item['car_name'] = $item['brand']['name'].$item['series']['name'];
            $item['edit'] = 0;
            $item['phone_arr'] = explode(',',$item['phone']);
            if (MemberVo::instance()->getShopId() > 0){ //处于商家端
                if ($item['type'] == 2 && $item['shop_id'] == MemberVo::instance()->getShopId()){
                    $item['edit'] = 1;
                }
            }else{//处于车主端
                if ($item['type'] == 1 && $item['member_id'] == MemberVo::instance()->getMemberId()){
                    $item['edit'] = 1;
                }
            }

            unset($item['shop'],$item['brand'],$item['series'],$item['member']);
            return $item;
        });
//        echo $this->model->getLastSql();die;
    }

    /**
     * 车辆编辑
     * @return ServiceShop|null
     * @throws ApiException
     * @throws \think\exception\DbException
     */
    public function car_edit($params)
    {
        try{
            $params['member_id'] = MemberVo::instance()->getMemberId();
            $shop_id = MemberVo::instance()->getShopId();
            if (isset($params['models_id']) && !empty($params['models_id'])){
                //根据车系获取品牌
                $models_info = CarModels::get($params['models_id']);
                if (empty($models_info))
                    throw new Exception("车型信息不存在");
                $params['brand_id'] = $models_info['brand_id'];
                $params['series_id'] = $models_info['series_id'];
            }else{
                if (isset($params['series_id']) && !empty($params['series_id'])){
                    //根据车系获取品牌
                    $series_info = CarSeries::get($params['series_id']);
                    if (empty($series_info))
                        throw new Exception("车系信息不存在");
                    $params['brand_id'] = $series_info['brand_id'];
                    $params['models_id'] = 0;
                }
            }
            $params['car_age'] =  floor($params['car_age']/1000); //转换为秒
            //获取行政信息
            $location = reverseGeocoding($params['latitude'],$params['longitude']);
            $amaps = getAmaps();
            $params['province'] = getNameByChar($amaps,$location->province)['id'];//省份
            $params['city'] = getNameByChar($amaps,$location->city)['id'];//城市
            $params['districts'] = getNameByChar($amaps,$location->district)['id'];//县区
            //手机号格式处理
            if (isset($params['phone_arr'])){
                $params['phone'] =  implode(',',$params['phone_arr']); //多电话格式
            }
            if (isset($params['id']) && !empty($params['id'])){ //更新
                $res = UsedCar::updateCar($params);
                ServiceImage::where(['main_id'=>$params['id'],'service_type'=>1])->delete();
                if (!empty($params['images'])){
                    foreach ($params['images'] as $v){
                        ServiceImage::create(['main_id'=>$params['id'],'image'=>$v,'service_type'=>1]);
                    }
                }
                $qrcode_url = mkQrcodeCode(Env::get('app.app_host')."/business/car_details?shopid={$params['id']}&shopType=1&shopTitle=二手车",md5(time().rand(1000,9999)),'uploads/business_qrcode/');
                $res->preview_qrcode = $qrcode_url;
                $res->save();
            }else{ //添加
                $params['type'] = 1;
                if ($shop_id > 0){
                    $params['shop_id'] = $shop_id;
                    $params['type'] = 2;
                }
                $res = UsedCar::addCar($params);
                //生成二维码
                $qrcode_url = mkQrcodeCode(Env::get('app.app_host')."/business/car_details?shopid={$res->id}&shopType=1&shopTitle=二手车",md5(time().rand(1000,9999)),'uploads/business_qrcode/');
                $res->preview_qrcode = $qrcode_url;
                $res->save();
                if (!empty($params['images'])){
                    foreach ($params['images'] as $v){
                        ServiceImage::create(['main_id'=>$res->id,'image'=>$v,'service_type'=>1]);
                    }

                }
            }
            $admins = Admin::where(['status'=>'normal','member_id'=>['gt',0]])->select();
            $member_name = Member::where('id',$params['member_id'])->value('member_name');
            Message::create(['content'=>"车主：".$member_name.',发起商机工单审核申请']);//发送站内信
            Log::info($member_name);
            foreach ($admins as $v){
                Queue::push(\app\job\Message::class,[
                    'member_id'=>$v['member_id'],
                    'template_id'=>config('wechat_gzh')['gzh_template']['gd_wait_audit'],
                    'data'=>[
                        'thing13'=>"待处理商机工单",
                        'phrase3'=> $shop_id>0 ? '商家':'车主',
                        'time4'=>date('Y-m-d H:i')
                    ]
                ],'message');
            }
            return true;
        }catch (Exception $e){
            throw new ApiException($e->getMessage(),404);
        }
    }

    /**
     * 获取车辆信息
     * @return ServiceShop|null
     * @throws ApiException
     * @throws \think\exception\DbException
     */
    public function info($params)
    {
        $params['member_id'] = MemberVo::instance()->getMemberId();
        $info = UsedCar::get($params['id'],['series','brand']);
        if (!$info)
            throw new ApiException('查无该车辆信息',404);
        if (MemberVo::instance()->getShopId() > 0){ //处于商家端
            if ($info['shop_id'] != MemberVo::instance()->getShopId()){
                throw new ApiException('无该二手车编辑权限',404);
            }
        }else{
            if ($info['member_id'] != MemberVo::instance()->getMemberId()){
                throw new ApiException('无该二手车编辑权限',404);
            }
        }
        $info['car_age'] = $info['car_age'] * 1000;
        $info['car_name'] = $info['brand']['name'].$info['series']['name'];
        $info['images'] = ServiceImage::field('image url')->where(['main_id'=>$info['id'],'service_type'=>1])->select();
        $info['phone_arr'] = explode(',',$info['phone']);
        unset($info['brand'],$info['series']);
        return $info;
    }

    /**
     * 获取车辆详情
     * @return ServiceShop|null
     * @throws ApiException
     * @throws \think\exception\DbException
     */
    public function detail($params)
    {
        $params['member_id'] = MemberVo::instance()->getMemberId();
        $info = UsedCar::get($params['id'],['models','series','brand','cartype','level','discharge','gearbox','swept'])->toArray();
        if (!$info)
            throw new ApiException('查无该车辆信息',404);
        $info['edit'] = 0;//可编辑状态 0不能编辑 1可以编辑
        if (MemberVo::instance()->getShopId() > 0){ //处于商家端
            if ($info['shop_id'] == MemberVo::instance()->getShopId()){
                $info['edit'] = 1;
            }
        }else{
            if ($info['type'] == 1 && $info['member_id'] == MemberVo::instance()->getMemberId()){
                $info['edit'] = 1;
            }
        }
        if ($info['shop_id'] > 0){
            $info['shop_name'] = Shop::where('id',$info['shop_id'])->value('shop_name');
        }else{
            $info['shop_name'] = Member::where('id',$info['member_id'])->value('member_name');
        }
        $info['car_type_name'] = $info['cartype']['name'] ?? '';
        $info['gearbox'] = $info['gearbox']['name'] ?? '';
        $info['level'] = $info['level']['name'] ?? '';
        $info['swept_volume'] = $info['swept']['name'] ?? '';
        $info['discharge'] = $info['discharge']['name'] ?? '';
        $info['car_type_name'] = $info['cartype']['name'] ?? '';
        $info['mileage'] = $info['mileage'].'万公里';
        $info['price'] = sprintf("%01.2f", $info['price']).'万元';
        $info['down_payment'] = empty($info['down_payment']) ? '' : sprintf("%01.2f", $info['down_payment']);
        $dif =  getMonthNum($info['car_age'],time());
        $str = '';
        if ($dif[1] >0){
            $str = $dif[1].'年';
        }
        if ($dif[2] >0){
            $str = $str.$dif[2].'月';
        }
        $info['car_name'] = $info['brand']['name'].$info['series']['name'].$info['models']['name'].$info['models']['year'];
        $info['createtime'] = date('Y.m.d',$info['createtime']);
        $info['car_age'] = $str;
        $info['images'] = ServiceImage::where(['main_id'=>$info['id'],'service_type'=>1])->select()->column('image');
        $collection = Collection::get(['main_id'=>$info['id'],'service_type'=>1,'member_id'=>MemberVo::instance()->getMemberId()]);
        $info['is_collection'] = !empty($collection) ? 1 : 0;
        $info['collection_id'] = !empty($collection) ? intval($collection['id']) : 0;
        $info['phone_arr'] = explode(',',$info['phone']);
        unset($info['brand'],$info['series'],$info['models'],$info['cartype'],$info['swept']);
        return $info;
    }


    /**
     * 我的二手车列表
     * @param array $params
     */
    public function my_index($params)
    {
        $params['is_del'] = 0;
        $params['with'] = ['series','brand','shop','member'];
        $params['orderBy'] = 'used_car.id';
        $params['orderType'] = 'desc';
        $params['field'] = 'id,car_age,show,status,mileage,phone,price,member_id,cover_img,down_payment,type,shop_id,longitude,latitude';
        return  $this->getPageList($params)->each(function (&$item){
            if ($item['type'] == 2){
                $item['shop_name'] = $item['shop']['shop_name'];
            }else{
                $item['shop_name'] = $item['member']['member_name'];
            }
            $dif =  getMonthNum($item['car_age'],time());
            $str = '';
            if ($dif[1] >0){
                $str = $dif[1].'年';
            }
            if ($dif[2] >0){
                $str = $str.$dif[2].'月';
            }
            $item['car_age'] = $str;
            $item['mileage'] = $item['mileage'].'万公里';
            $collection = Collection::get(['main_id'=>$item['id'],'service_type'=>1,'member_id'=>MemberVo::instance()->getMemberId()]);
            $item['is_collection'] = !empty($collection) ? 1 : 0;
            $item['collection_id'] = !empty($collection) ? intval($collection['id']) : 0;
            $item['price'] = sprintf("%01.2f", $item['price']).'万元';
            $item['down_payment'] = $item['down_payment'] ? sprintf("%01.2f", $item['down_payment']).'万元' : '';
            $item['car_name'] = $item['brand']['name'].$item['series']['name'];
            $item['edit'] = 1;
            unset($item['shop'],$item['brand'],$item['series'],$item['member']);
            return $item;
        });
    }


}